package com.chaos.meta.config;

import com.chaos.meta.entity.User;
import com.chaos.meta.service.UserService;
import com.chaos.meta.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author naicha
 */
//@Component
@Slf4j
public class LoginValidateAuthenticationProvider implements AuthenticationProvider
{
    private static Map<Class<?>, BadCredentialsException> EXCEPTION_MESSAGE = new HashMap<>();
    static{
        EXCEPTION_MESSAGE.put(User.class, new BadCredentialsException("This user doesn't exist!"));
        EXCEPTION_MESSAGE.put(String.class, new BadCredentialsException("Incorrect password!"));
        EXCEPTION_MESSAGE.put(Integer.class, new BadCredentialsException("Role mismatch!"));
    }

    @Autowired
	private UserService sUser;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // get input userName
        String userName = authentication.getName();
        // get input rawPassword
        String rawPassword = (String) authentication.getCredentials();
        // get worldName by custom Details class
        CustomAuthenticationDetailsSource.CustomWebAuthenticationDetails details = (CustomAuthenticationDetailsSource.CustomWebAuthenticationDetails) authentication.getDetails();
        String otherInfo = details.getOtherInfo();

        User user = sUser.findByName(userName);
        if (user == null)
        {
            throw EXCEPTION_MESSAGE.get(User.class);
        }else {
            // validate password
            rawPassword = StringUtil.digestPassword(userName, rawPassword);
            String passwordFromDB = user.getPassword();
            if (!passwordFromDB.equals(rawPassword)) {
                throw EXCEPTION_MESSAGE.get(String.class);
            }
        }
        return new UsernamePasswordAuthenticationToken(user, rawPassword, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication)
    {
        // 确保authentication能转成该类
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}